<template>
    <div class="sceditor">
        <Editor id="tinymceId" v-model="contentValue" :init="init" :placeholder="placeholder" @onClick="onClick" />
        <van-popup v-model="showCustomUpImage">
            <div class="customImg">
                <h3>上传图片</h3>
                <van-uploader :max-count="1" :after-read="customImgAfterRead" :max-size="8 * 1024 * 1024" @oversize="onOversize"></van-uploader>
            </div>
        </van-popup>
    </div>
</template>

<script>
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver/theme";
// 这里引入报错可以替换成 import 'tinymce/themes/modern/theme'import "tinymce/icons/default";  //显示富文本图标，如果不加富文本图标显示会变成 !not found

import "tinymce/themes/silver";
import "tinymce/icons/default";
// import "tinymce/models/dom";

// 引入编辑器插件
import "tinymce/icons/default/icons";
import "tinymce/plugins/code"; //编辑源码
import "tinymce/plugins/image"; //插入编辑图片
import "tinymce/plugins/media"; //插入视频
import "tinymce/plugins/link"; //超链接
import "tinymce/plugins/preview"; //预览
import "tinymce/plugins/template"; //模板
import "tinymce/plugins/table"; //表格
import "tinymce/plugins/pagebreak"; //分页
import "tinymce/plugins/lists"; //列
import "tinymce/plugins/advlist"; //列
import "tinymce/plugins/quickbars"; //快速工具条
import "tinymce/plugins/fullscreen"; //全屏
import "tinymce/plugins/wordcount";

import zh_CN from "./zh_CN.js";

import { uploadImg } from "@/https/api";
import { Toast } from "vant";
export default {
    components: {
        Editor,
    },
    props: {
        draftType: {
            type: Number,
            default: 1,
        },
        value: {
            type: String,
            default: "",
        },
        placeholder: {
            type: String,
            default: "",
        },
        height: {
            type: Number,
            default: 500,
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        plugins: {
            type: [String, Array],
            default: "code image media link preview table quickbars template pagebreak lists advlist",
        },
        // toolbar: {
        //     type: [String, Array],
        //     default:
        //         "undo redo bold italic underline strikethrough alignleft | aligncenter alignright  alignjustify formatselect fontselect fontsizeselect fontfamily fontsize blocks outdent indent numlist bullist forecolor backcolor removeformat pagebreak charmap fullscreen insertfile preview",
        // },
        templates: {
            type: Array,
            default: () => [],
        },
    },
    data() {
        let _this = this;
        return {
            fullscreen: false,
            showCustomUpImage: false,
            myEditor: null,
            init: {
                selector: "#tinymceId",
                language_url: zh_CN,
                language: "zh_CN",
                skin_url: "./skins/ui/oxide",
                content_css: "./skins/content/default/content.css",
                menubar: false,
                statusbar: true,
                plugins: this.plugins,
                toolbar: `undo redo ${
                    _this.draftType == 2 ? "customImage" : ""
                } bold italic underline strikethrough alignleft | aligncenter alignright  alignjustify formatselect fontselect fontsizeselect fontfamily fontsize blocks outdent indent numlist bullist forecolor backcolor removeformat pagebreak charmap fullscreen insertfile preview`,
                toolbar_mode: "floating",
                body_class: "panel-body ",
                // object_resizing: false,
                font_formats:
                    "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';等线='等线';方正姚体='方正姚体';方正舒体='方正舒体';华文仿宋='华文仿宋';华文楷体='华文楷体';华文隶属='华文隶属';华文细黑='华文细黑';微软雅黑='微软雅黑';新宋体='新宋体';华文行楷='华文行楷';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
                fontsize_formats: "12px 14px 16px 18px 20px 22px 24px 26px 28px 30px 32px 34px 36px",
                advlist_number_styles: "default",
                end_container_on_empty_block: true,
                powerpaste_word_import: "clean",
                advlist_bullet_styles: "square",
                height: this.height,
                placeholder: this.placeholder,
                branding: false,
                resize: true,
                elementpath: true,
                content_style: "",
                templates: this.templates,
                quickbars_selection_toolbar: "forecolor backcolor bold italic underline strikethrough link",
                quickbars_image_toolbar: "alignleft aligncenter alignright",
                quickbars_insert_toolbar: false,
                image_caption: true,
                image_advtab: true,
                contextmenu: ' ',
                mobile: {
                    plugins: this.plugins,
                    toolbar: `undo redo ${
                        _this.draftType == 2 ? "customImage" : ""
                    } bold italic underline strikethrough alignleft | aligncenter alignright  alignjustify formatselect fontselect fontsizeselect fontfamily fontsize blocks outdent indent numlist bullist forecolor backcolor removeformat pagebreak charmap fullscreen insertfile preview`,
                    toolbar_mode: "sliding",
                    height: this.height,
                    contextmenu: ' ',
                    // automatic_uploads: false,
                    // min_height: this.height,
                },
                setup: function (editor) {
                    _this.myEditor = editor;
                    editor.on("input", function (e) {
                        console.log(e.inputType);
                        // && e.inputType != 'insertCompositionText'
                        if (e.inputType != "insertText" && e.inputType != "insertFromComposition") {
                            var pattern = new RegExp("[\u4E00-\u9FA5]+");
                            if (e.data && pattern.test(e.data)) {
                                editor.insertContent(e.data || "");
                            }
                        }
                    });
                    //定义一个名为 customImage 的toolbar
                    editor.ui.registry.addButton("customImage", {
                        text: `<svg width="24" height="24"><path d="M5 15.7l3.3-3.2c.3-.3.7-.3 1 0L12 15l4.1-4c.3-.4.8-.4 1 0l2 1.9V5H5v10.7zM5 18V19h3l2.8-2.9-2-2L5 17.9zm14-3l-2.5-2.4-6.4 6.5H19v-4zM4 3h16c.6 0 1 .4 1 1v16c0 .6-.4 1-1 1H4a1 1 0 01-1-1V4c0-.6.4-1 1-1zm6 8a2 2 0 100-4 2 2 0 000 4z" fill-rule="nonzero"></path></svg>`,
                        tooltip: "上传图片",
                        onAction: () => {
                            _this.showCustomUpImage = true;
                        },
                    });
                },
            },
            contentValue: this.value,
        };
    },
    watch: {
        value(val) {
            this.contentValue = val;
        },
        contentValue(val) {
            this.$emit("update:value", val);
        },
    },
    mounted() {
        tinymce.init({});
    },

    methods: {
        Input_ValidateNum(valDom) {
            var isInputZh = false;
            var search = document.getElementById('tinymceId');
            search.addEventListener(
                "compositionstart",
                function (e) {
                    isInputZh = true;
                },
                false
            );
            search.addEventListener(
                "compositionend",
                function (e) {
                    isInputZh = false;
                    ValidateNum(valDom); //这个方法可以随意更换，是用来处理输入数据的
                },
                false
            );
            search.addEventListener(
                "input",
                function (e) {
                    if (isInputZh) return;
                    ValidateNum(valDom); //这个方法可以随意更换，是用来处理输入数据的
                },
                false
            );
        },
        destroyTinymce() {
            if (tinymce) {
                tinymce.destroy();
            }
        },
        onClick(e) {
            this.$emit("onClick", e, tinymce);
        },
        blur() {
            console.log(this.myEditor);
        },
        focus() {
            console.log("focus");
        },
        onOversize() {
            Toast("封面图大小不能超过 8MB");
        },
        async customImgAfterRead(file) {
            this.showCustomUpImage = false;
            Toast.loading({
                duration: 0,
                forbidClick: true,
                message: "图片上传中...",
            });
            let formData = new FormData();
            formData.append("file", file.file);
            let res = await uploadImg(formData);
            Toast.clear();
            if (res.code === 1) {
                Toast("上传成功");
                this.myEditor.insertContent(`<img src="${res.data.url}">`);
            } else {
                Toast("上传失败");
            }
        },
    },
};
</script>

<style lang="scss" scoped>
.sceditor {
    width: 100%;
}

.customImg {
    width: 4.6rem;
    padding: 0.3rem;
    box-sizing: border-box;
    text-align: center;
}
.customImg h3 {
    margin-bottom: 0.3rem;
}
.tinymce-container {
    position: relative;
    line-height: normal;
}
.tinymce-container >>> .mce-fullscreen {
    z-index: 10000;
}
.tinymce-textarea {
    visibility: hidden;
    z-index: -1;
}
.editor-custom-btn-container {
    position: absolute;
    right: 4px;
    top: 4px;
    z-index: 2005;
}
.fullscreen .editor-custom-btn-container {
    z-index: 10000;
    position: fixed;
}
.editor-upload-btn {
    display: inline-block;
}
.myFixed {
    position: fixed;
    top: 5px;
    right: 45px;
}
.panel-body {
    height: 100%;
}
</style>
